<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from "vue";
import {
  reqTrademarkList,
  reqSaveOrUpdateTrademark,
  reqDeleteTrademark,
} from "@/api/product/trademark";
import type { trademark } from "@/api/product/trademark/type";
import { ElMessage, UploadProps } from "element-plus";
import {
  trademarkResponseData,
  trademarkList,
} from "@/api/product/trademark/type";
// 起始页码
let pageNo = ref<number>(1);
// 每页个数
let limit = ref<number>(3);
// 总数据条数
let total = ref<number>(0);
// table表格data字段要展示的数组
let trademarkList = ref<trademarkList>([]);
// 控制dialog会话框是否显示的字段
let dialogFormVisible = ref<boolean>(false);
// 该字段用于收集用于新增和修改品牌接口的参数
let trademarkParams = reactive<trademark>({
  logoUrl: "",
  tmName: "",
});
// 该字段用来获取el-form的组件实例(vc)
const formRef = ref();
// onMounted钩子
onMounted(() => {
  getTrademarkList();
});
// 一个解决后端接口错误的函数
let dealImages: any = (records: Array<any>) => {
  if (pageNo.value === 1) {
    records.shift();
    records.push({
      id: 24,
      logoUrl:
        "http://39.98.123.211/group1/M00/02/DC/rBHu8mGyMaWAW-TWAAAIiNxy53s540.jpg",
      tmName: "联想",
    });
  }
};

// 获取品牌列表的函数
const getTrademarkList = async (pager = 1) => {
  let res: trademarkResponseData = await reqTrademarkList(
    (pageNo.value = pager),
    limit.value
  );
  dealImages && dealImages(res.data.records);

  if (res.code == 200) {
    total.value = res.data.total;
    trademarkList.value = res.data.records;
  }
};
// 每页数据条数发生变化时的回调
const sizeChangeHandler = () => {
  // 每页数据条数发生变化时，页码回到第一页
  pageNo.value = 1;
  getTrademarkList();
};
// 添加品牌的回调
const addTrademark = () => {
  // 清空表单数据
  trademarkParams.logoUrl = "";
  trademarkParams.tmName = "";
  trademarkParams.id = 0;
  dialogFormVisible.value = true;
  // 清空表单错误的信息
  nextTick(() => {
    formRef.value.clearValidate("tmName");
    formRef.value.clearValidate("logoUrl");
  });
};
// 修改品牌的回调
const updateTrademark = async (row: any) => {
  dialogFormVisible.value = true;
  // 让会话框内显示对应的数据
  trademarkParams.logoUrl = row.logoUrl;
  trademarkParams.tmName = row.tmName;
  trademarkParams.id = row.id;
  // 清空表单错误的信息
  nextTick(() => {
    formRef.value.clearValidate("tmName");
    formRef.value.clearValidate("logoUrl");
  });
};
// dialog底部取消按钮的回调
const cancel = () => {
  dialogFormVisible.value = false;
};
// dialog底部确定按钮的回调
const confirm = async () => {
  // 对整个表单进行验证
  await formRef.value.validate();
  // 关闭会话框
  dialogFormVisible.value = false;
  // 调用添加或更改品牌的接口
  let res: any = await reqSaveOrUpdateTrademark(trademarkParams);
  if (res.code == 200) {
    // ELMessage提示
    ElMessage({
      type: "success",
      message: trademarkParams.id ? "修改品牌成功" : "添加品牌成功",
    });
    // 重新发请求捞数据
    getTrademarkList(pageNo.value);
  } else {
    ElMessage({
      type: "error",
      message: trademarkParams.id ? "修改品牌失败" : "添加品牌失败",
    });
  }
};
// 文件上传成功的回调
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response: any,
  uploadFile: any
) => {
  if (response.code == 200) {
    // 收集logoUrl字段
    trademarkParams.logoUrl = response.data;
    // 用于清空logoUrl的失败上传验证信息
    formRef.value.clearValidate("logoUrl");
    return true;
  } else {
    return false;
  }
};
// 在文件上传完毕之前的钩子
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile: any) => {
  // 项目要求：只能上传jpeg | png | gif 格式的文件，且文件大小小于4MB
  if (
    rawFile.type == "image/png" ||
    rawFile.type == "image/jpeg" ||
    rawFile.type == "image/gif"
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true;
    } else {
      ElMessage({
        type: "error",
        message: "上传文件大小大于4MB",
      });
      return false;
    }
  } else {
    ElMessage({
      type: "error",
      message: "上传的文件务必是png|jpg|gif格式",
    });
    return false;
  }
};
// 验证tmName字段的规则函数
const validateTmName = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 2 && value.trim().length <= 10) {
    callback();
  } else {
    callback(new Error("品牌名称必须大于等于两位并小于十位"));
  }
};
// 验证logoUrl字段的规则函数
const validateLogoUrl = (rule: any, value: any, callback: any) => {
  if (value) {
    callback();
  } else {
    callback(new Error("品牌Logo不能为空"));
  }
};
// dialog会话框中的表单验证规则
const rules = {
  tmName: [
    {
      required: true,
      trigger: "blur",
      validator: validateTmName,
    },
  ],
  logoUrl: [
    {
      required: true,
      validator: validateLogoUrl,
    },
  ],
};
// popconfirm确定删除trademark的回调
const deleteTrademark = async (id: number) => {
  let res = await reqDeleteTrademark(id);
  if (res.code == 200) {
    ElMessage({
      type: "success",
      message: "删除品牌成功",
    });
    getTrademarkList(
      trademarkList.value.length == 1 ? pageNo.value - 1 : pageNo.value
    );
  } else {
    ElMessage({
      type: "error",
      message: "删除品牌失败",
    });
  }
};
</script>

<template>
  <div>
    <el-card v-if="trademarkList[0]">
      <el-button
        type="primary"
        icon="Plus"
        @click="addTrademark"
        v-have="`btn.Trademark.add`"
        >添加品牌</el-button
      >
      <el-table
        style="width: 100%; margin: 10px 0"
        border
        :data="trademarkList"
      >
        <el-table-column
          prop="prop"
          label="序号"
          width="80px"
          type="index"
          align="center"
        >
        </el-table-column>
        <el-table-column label="品牌名称" prop="tmName"> </el-table-column>
        <el-table-column label="品牌LOGO">
          <template v-slot="{ row, $index }">
            <img
              v-lazy-load="row.logoUrl"
              alt="图片加载失败"
              style="width: 100px; height: 100px"
            />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template v-slot="{ row, $index }">
            <el-button
              type="warning"
              size="default"
              icon="Edit"
              @click="updateTrademark(row)"
              v-have="`btn.Trademark.update`"
            ></el-button>
            <el-popconfirm
              :title="`您确定要删除${row.tmName}吗`"
              width="200px"
              icon="Delete"
              @confirm="deleteTrademark(row.id)"
            >
              <template #reference>
                <el-button
                  type="danger"
                  size="default"
                  icon="Delete"
                  v-have="`btn.Trademark.remove`"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        layout="prev, pager, next,jumper, ->,sizes, total"
        v-model:page-size="limit"
        v-model:current-page="pageNo"
        :page-sizes="[3, 5, 10]"
        :total="total"
        background
        @current-change="getTrademarkList"
        @size-change="sizeChangeHandler"
      >
      </el-pagination>
    </el-card>
    <!-- dialog会话框 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
    >
      <el-form
        style="width: 80%"
        :model="trademarkParams"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input autocomplete="off" v-model="trademarkParams.tmName" />
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <!-- upload文件上传 -->
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- dialog底部具名插槽 #footer 或 v-slot:footer -->
      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="confirm"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
